package netty.http.handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.net.URI;

/**
 * @ClassName TestHttpServerHandler
 * @Description TODO
 * @Author director吴
 * @Date 2022/2/16 13:02
 * @Version 1.0
 *
 * 接收信息 或者 发送信息
 **/
public class TestHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {

    // channelRead0 读取客户端数据
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {

        if(msg instanceof HttpRequest){


            System.out.println("piepline="+ctx.pipeline().hashCode());
            System.out.println("TestHandler -Hash=" + this.hashCode());

            System.out.println("msg类型="+msg.getClass());
            System.out.println("客户端地址="+ctx.channel().remoteAddress());


            /**
             * 通过url过滤指定
             */
             HttpRequest httpRequest = (HttpRequest) msg;

             //获取url
            URI uri = new URI(httpRequest.uri());

            if ("/favicon.ico".equals(uri.getPath())){
                System.out.println("请求了--ico，不响应");
                return;
            }

            //回复浏览器
           ByteBuf buf =  Unpooled.copiedBuffer("-aaa我是服务器", CharsetUtil.UTF_8);

            /**    ---构造Http Response
             *   HTTP版本： HttpVersion.HTTP_1_1
             *   HTTP状态： HttpResponseStatus.OK
             */
            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,buf);


            response.headers().set(HttpHeaderNames.CONTENT_TYPE ,"text/plain;charset=UTF-8");//设置 -文本类型
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH,buf.readableBytes()); //

            //将构建好的 response 返回
            ctx.writeAndFlush(response);

        }


    }
}
